#!/usr/bin/env python
# @Date    : 2022-04-25
# @Author  : Bright (brt2@qq.com)
# @Link    : https://gitee.com/brt2
# @Version : 0.2.1

_g = {
    "app": None,
    "static_folder": None
}

def app_run(app, *args, **kwargs):
    # export FLASK_ENV=development
    # Run: flask run -h '0.0.0.0' -p 1124
    if "reload" in kwargs:
        del kwargs["reload"]
    return app.run(*args, **kwargs)

def make_app(app_name, **kwargs):
    from flask import Flask as Application

    if not _g.get("app"):
        app = Application(app_name,
                template_folder=kwargs.get("template_folder", "static"))
        # 配置static目录
        if _g["static_folder"] is not None:
            app.static_folder = _g["static_folder"]
        # 解决flask缓存问题
        from datetime import timedelta
        app.config["SEND_FILE_MAX_AGE_DEFAULT"] = timedelta(seconds=1)

        _g["app"] = app
    return _g["app"]

#####################################################################
# 功能函数
#####################################################################

from flask import url_for, redirect

def set_static_path(path_dir):
    # assert _g["app"], "请先创建app，再执行当前操作"
    if _g["app"] is None:
        _g["static_folder"] = path_dir
    else:
        _g["app"].static_folder = path_dir

#####################################################################
# web
#####################################################################

from flask import render_template, render_template_string
from flask import render_template as static_file

#####################################################################
# request, response
#####################################################################

from flask import request

def request_data(type_):
    # request.args和request.form都包含在request.values里面。即把两个列表拼接后，转换成一个字典
    # 当request.args和request.form都有同一个键时，因为form会被先序列化，args的值会覆盖form的值
    if type_ == "form":
        # 请求体的表单数据
        return request.form
    elif type_ == "query":
        # URL传参的数据
        return request.args
    elif type_ == "header":
        return request.headers
    elif type_ == "cookie":
        return request.cookies
    elif type_ == "json":
        # 设置了Content-Type:application/json的Body数据只能通过request.json获取
        return request.json
    elif type_ == "bytes":
        # request.data返回的数据是一个bytes类型
        return request.data
    elif type_ == "file":
        # request.files接收的是form表单中<input type="file" name="file"/>传过过来的数据
        return request.files
    else:
        NotImplementedError(f"未实现【{type_}】类型的request解析")
